{"componentChunkName":"component---src-templates-post-jsx","path":"/[Algorithm]다익스트라알고리즘/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"268a7d15-795c-5e9f-9770-eeda9132721d","excerpt":"🧷 다익스트라(Dijkstra) 알고리즘 DP를 활용한 최단 경로 탐색 알고리즘으로, 시작 정점  에서부터 다른 정점들까지의 최단 거리를 계산한다. DP가 적용되는 이유는, 굳이 한 번 최단 거리를 구한 곳은 다시 구할 필요가 없기 때문이다. 그리고 이를 활용해 정점에서 정점까지 간선을 따라 이동할 때 최단 거리를 효율적으로 구할 수 있다. 간선의 값이 …","html":"<h2>🧷 다익스트라(Dijkstra) 알고리즘</h2>\n<p>DP를 활용한 최단 경로 탐색 알고리즘으로, 시작 정점 <code class=\"language-text\">s</code> 에서부터 다른 정점들까지의 최단 거리를 계산한다.</p>\n<ul>\n<li>DP가 적용되는 이유는, 굳이 한 번 최단 거리를 구한 곳은 다시 구할 필요가 없기 때문이다.</li>\n<li>그리고 이를 활용해 정점에서 정점까지 간선을 따라 이동할 때 최단 거리를 효율적으로 구할 수 있다.</li>\n</ul>\n<blockquote>\n<p>간선의 값이 양수인 경우만 알고리즘을 사용할 수 있다.</p>\n</blockquote>\n<blockquote>\n<p><strong>음수 간선이 존재하면 안되는 이유?</strong>\n<img src='https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&amp;fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2Fc3lSDe%2Fbtrhn3zNgfu%2FctA1FRLMWNuzRvvssYPIkk%2Fimg.png' width='30%'></p>\n<ul>\n<li>위 경우, A에서 출발하여 <code class=\"language-text\">dist[B] = 10</code> , <code class=\"language-text\">dist[C] = 4</code> 로 업데이트한 후,</li>\n<li>가장 비용이 작은 C로 이동할 것이다. 그렇게 되면, 더 이상 C의 거리가 갱신될 일이 없어 -90이 아닌 4로 종료된다.</li>\n</ul>\n<p>하지만, 우선순위 큐를 사용해 방문한 정점에 대해서 재방문하여 최소 비용을 저장한다면 음수 가중치에 대한 계산이 가능하다. 이는 아래에서 구현한다.</p>\n</blockquote>\n<img src='https://upload.wikimedia.org/wikipedia/commons/5/57/Dijkstra_Animation.gif' width='70%'>\n<p>다익스트라 알고리즘의 구현을 위해 2가지를 저장해야 한다.</p>\n<ul>\n<li>해당 정점까지의 최단 거리</li>\n<li>정점 방문 여부</li>\n</ul>\n<h3>🪚 과정</h3>\n<ol>\n<li>최단 거리 값은 무한대 값으로 초기화</li>\n<li>시작 정점의 최단 거리는 0이다. (방문 처리)</li>\n<li>시작 정점과 연결된 정점들의 최단 거리 값을 갱신</li>\n<li>방문하지 않은 정점 중 최단 거리가 최소인 정점을 탐색</li>\n<li>찾은 정점을 방문 체크하고, 해당 정점과 연결된 미방문 정점의 최단 거리 값을 갱신</li>\n<li>모든 정점을 방문할 때까지 4~5번 반복</li>\n</ol>\n<h3>🪚 시간 복잡도</h3>\n<ul>\n<li>인접 행렬 구현 시: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><msup><mi>N</mi><mn>2</mn></msup><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(N^2)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1.064108em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord\"><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"msupsub\"><span class=\"vlist-t\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.8141079999999999em;\"><span style=\"top:-3.063em;margin-right:0.05em;\"><span class=\"pstrut\" style=\"height:2.7em;\"></span><span class=\"sizing reset-size6 size3 mtight\"><span class=\"mord mtight\">2</span></span></span></span></span></span></span></span><span class=\"mclose\">)</span></span></span></span></li>\n<li>인접 리스트 구현 시: <span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mi>O</mi><mo stretchy=\"false\">(</mo><mi>N</mi><mi>l</mi><mi>o</mi><mi>g</mi><mi>N</mi><mo stretchy=\"false\">)</mo></mrow><annotation encoding=\"application/x-tex\">O(NlogN)</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:1em;vertical-align:-0.25em;\"></span><span class=\"mord mathnormal\" style=\"margin-right:0.02778em;\">O</span><span class=\"mopen\">(</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mord mathnormal\" style=\"margin-right:0.01968em;\">l</span><span class=\"mord mathnormal\">o</span><span class=\"mord mathnormal\" style=\"margin-right:0.03588em;\">g</span><span class=\"mord mathnormal\" style=\"margin-right:0.10903em;\">N</span><span class=\"mclose\">)</span></span></span></span></li>\n</ul>\n<h3>🪚 일종의 개선?</h3>\n<p><strong>우선순위 큐</strong>를 사용해 거리가 가장 가까운 정점부터 방문할 수 있도록 한다.</p>\n<ul>\n<li>우선순위 큐에 정점의 번호와 지금까지 찾아낸 해당 정점까지의 최단 거리를 쌍으로 저장한다.</li>\n<li>아직 방문하지 않은 정점 중 시작점으로부터의 거리가 가장 가까운 점을 찾는 과정을 간단하게 해준다.</li>\n</ul>\n<p>우선순위 큐를 사용한따는 점을 제외하면, BFS와 비슷한 구조의 알고리즘이다.</p>\n<ul>\n<li>각 정점까지의 최단 거리를 저장하는 배열을 유지하며,</li>\n<li>정점 방문마다 인접한 정점을 모두 검사한다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Pair implements Comparable&lt;Node&gt; {\n  int num;\n  int weight;\n\n  public Pair(int num, int weight) {\n    this.num = num;\n    this.weight = weight;\n  }\n\n  @Override\n  public int compareTo(Node n) {\n      return this.weight - n.weight;\n  }\n}\n\nint V;\nArrayList&lt;ArrayList&lt;Pair&gt;&gt; adjList = new ArrayList&lt;&gt;();\n\nint[] dijkstra(int src) {\n  int[] dist = new int[V];\n  Arrays.fill(dist, Integer.MAX_VALUE);\n  dist[src] = 0;\n\n  Queue&lt;Pair&gt; queue = new PriorityQueue&lt;&gt;();\n  queue.add(new Pair(src, 0));\n\n  while(!queue.isEmpty()) {\n    Pair p = queue.poll();\n    int here = p.num;\n    int cost = p.weight;\n\n    if (dist[here] &lt; cost) continue;\n\n    for (int i = 0; i &lt; adjList.get(here).size(); i++) {\n      int there = adjList.get(here).get(i).num;\n      int nextDist = cost + adjList.get(here).get(i).weight;\n\n      if (dist[there] &gt; nextDist) {\n        dist[there] = nextDist;\n        queue.add(new Pair(there, nextDist));\n      }\n    }\n  }\n}</code>\n        </deckgo-highlight-code>\n<hr>\n<h2>📕 참고</h2>\n<ul>\n<li><a href=\"https://gyoogle.dev/blog\">Tech Interview for developer</a></li>\n<li><a href=\"https://kangworld.tistory.com/76\">[Algorithm] 다익스트라 알고리즘 : 음수 간선이 있으면 안 되는 이유</a></li>\n<li>[<strong>프로그래밍 대회에서 배우는 알고리즘 문제 해결 전략</strong>] 구종만</li>\n</ul>","frontmatter":{"title":"💡 다익스트라(Dijkstra) 알고리즘","date":"May 13, 2022","update":"May 13, 2022","tags":["개발상식","Java","Dijkstra"],"series":"💡 Algorithm"},"fields":{"slug":"/[Algorithm]다익스트라알고리즘/","readingTime":{"minutes":4.34}}},"seriesList":{"edges":[{"node":{"id":"b0e662c4-8dab-58b1-8e34-76fd1f26ad52","fields":{"slug":"/[Algorithm]graph/"},"frontmatter":{"title":"💡 Graph 이론"}}},{"node":{"id":"c1c6944f-734a-5276-8604-a897181207ae","fields":{"slug":"/[Algorithm]문제해결개관/"},"frontmatter":{"title":"💡 문제해결개관"}}},{"node":{"id":"b783c57f-f958-5c14-9935-06b16995e8f1","fields":{"slug":"/[Algorithm]알고리즘분석/"},"frontmatter":{"title":"💡 알고리즘 분석"}}},{"node":{"id":"f3c7f32a-2ead-5bd5-a198-ee5342823217","fields":{"slug":"/[Algorithm]Sorting 알고리즘/"},"frontmatter":{"title":"💡 Sorting 알고리즘"}}},{"node":{"id":"07844ce0-f154-5ad8-b4cc-c6e9bebecc21","fields":{"slug":"/[Algorithm]이분 탐색/"},"frontmatter":{"title":"💡 이분 탐색(Binary Search)"}}},{"node":{"id":"66ab5e60-ccc9-5f85-ad77-8457be4014db","fields":{"slug":"/[Algorithm]HashTable/"},"frontmatter":{"title":"💡 해시 테이블 (Hash Table)"}}},{"node":{"id":"8aa61523-9a0a-5cc7-a670-9750d851b450","fields":{"slug":"/[Algorithm]최장증가수열(LIS)/"},"frontmatter":{"title":"💡 최장 증가 수열(LIS)"}}},{"node":{"id":"db216133-c9cd-5948-babf-f437eb127d7c","fields":{"slug":"/[Algorithm]DynamicProgramming/"},"frontmatter":{"title":"💡 DP (Dynamic Programming)"}}},{"node":{"id":"fa96dd6e-75c9-5a7c-887c-1993125cc7f0","fields":{"slug":"/[Algorithm]최소공통조상(LCA)/"},"frontmatter":{"title":"💡 최소 공통 조상(LCA)"}}},{"node":{"id":"268a7d15-795c-5e9f-9770-eeda9132721d","fields":{"slug":"/[Algorithm]다익스트라알고리즘/"},"frontmatter":{"title":"💡 다익스트라(Dijkstra) 알고리즘"}}},{"node":{"id":"f3a9bade-22f4-54b0-ad9a-b642d6f2b754","fields":{"slug":"/[Algorithm]비트마스크/"},"frontmatter":{"title":"💡 비트마스크(BitMask)"}}}]},"previous":{"fields":{"slug":"/[Algorithm]최소공통조상(LCA)/"},"frontmatter":{"title":"💡 최소 공통 조상(LCA)"}},"next":{"fields":{"slug":"/[BOJ]16472/"},"frontmatter":{"title":"👩‍💻 16472. 고냥이"}}},"pageContext":{"id":"268a7d15-795c-5e9f-9770-eeda9132721d","series":"💡 Algorithm","previousPostId":"fa96dd6e-75c9-5a7c-887c-1993125cc7f0","nextPostId":"e13ff8d6-9b02-56c0-83e2-1d3144f70e1d"}},"staticQueryHashes":[]}